<template>
  <div id="yhList">
    <el-card class="box-card" style="height: 100%;" >
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input placeholder="请输入用户名查询" v-model="queryInfo.userName" class="input-with-select" clearable @clear="getUserList">
              <el-button  type="goon" round slot="append" icon="el-icon-search" @click="getUserList" ></el-button>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-input placeholder="请输入姓名查询" v-model="queryInfo.name" class="input-with-select" clearable @clear="getUserList">
              <el-button slot="append" type="goon" round icon="el-icon-search" @click="getUserList" ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4"><el-button type="goon" round @click="dialogVisible = true" v-has="'adduser'">添加用户</el-button></el-col>
        </el-row>
      </div>
      <div class="serverTable">
      <el-table
        :data="tableData"
        border
        height="100%"
        style="width: 100%">
        <el-table-column
          type="selection"
        >
        </el-table-column>
        <el-table-column
          type="index"
          label="#"
          min-width="2%"
        >
          <template v-slot="scope">
            {{ (queryInfo.pageNumber-1) * queryInfo.pageSize+ scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          min-width="10%"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          min-width="8%"
        >
        </el-table-column>
        <el-table-column
          label="角色"
          min-width="8%"
        >
          <template v-slot="scope">
            <span v-for="item in scope.row.roles" :key="item.id">{{item.roleName}} </span>
          </template>
        </el-table-column>
        <el-table-column
          label="部门"
          min-width="6%"
        >
          <template v-slot="scope">
            <span v-if="scope.row.unit">{{scope.row.unit["unitName"]}} </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="10%"
        >
        </el-table-column>
        <el-table-column
          prop="post"
          label="职务"
          min-width="6%"
        >
        </el-table-column>

        <!--<el-table-column-->
          <!--prop="telephone"-->
          <!--label="联系电话"-->
          <!--min-width="6%"-->
        <!--&gt;-->
        <!--</el-table-column>-->

        <el-table-column
          label="操作"
          min-width="9%"
        >
          <template v-slot="scope">
            <el-tooltip effect="dark" content="修改用户" placement="top" :enterable="false" v-has="'updateuser'">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.id)" ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false" v-has="'deleteuser'">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteMsg(scope.row.id)" ></el-button>
            </el-tooltip>
            <!--  <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
              </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNumber"
        :page-sizes="[5,10, 20, 50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      </div>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="25%"
      center
      :before-close="handleClose"
      @close="dialogClose"
    >
      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRule">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="addForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="juese" clearable  multiple placeholder="请选择角色" style="width: 100%" @change="jueseChange">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="unitId">
          <el-select v-model="addForm.unitId" clearable  placeholder="请选择部门" style="width: 100%" @change="bumenChange">
            <el-option
              v-for="item in bumenList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email"  >
          <el-input v-model="addForm.email" > </el-input>
        </el-form-item>
        <el-form-item label="职务" prop="post">
          <el-input v-model="addForm.post"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="addForm.telephone"></el-input>
        </el-form-item>
        <!--  <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="addForm.sex">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
       <el-button round type="goon" size="medium" @click="dialogVisible = false">取 消</el-button>
    <el-button round type="goon" size="medium"  @click="addUser" >确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      title="修改用户信息"
      :visible.sync="editdialogVisible"
      width="25%"
      center
      :before-close="handleClose"
      @close="editdialogClose"
    >
      <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="jueseEdit"  clearable  multiple placeholder="请选择角色" style="width: 100%" @change="jueseChange2">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="unitId">
          <el-select v-model="editForm.unitId" clearable  placeholder="请选择部门" style="width: 100%" @change="bumenChange2">
            <el-option
              v-for="item in bumenList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email"  >
          <el-input v-model="editForm.email" > </el-input>
        </el-form-item>
        <el-form-item label="职务" prop="post">
          <el-input v-model="editForm.post"></el-input>
        </el-form-item>
        <!--<el-form-item label="联系电话" prop="telephone">-->
          <!--<el-input v-model="editForm.telephone"></el-input>-->
        <!--</el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer">
     <el-button round type="goon" size="medium" @click="editdialogVisible = false">取 消</el-button>
    <el-button round type="goon" size="medium" @click="editUserInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  import md5 from 'js-md5';
  export default {
    name: 'yhLish',
    data(){
      var checkEmail=(rule,value,cb)=>{
        const regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
        if(value==""){
          return cb();
        }
        else if(regEmail.test(value)){
          return cb()
        }
        cb(new Error('请输入合法的邮箱！'))
      }
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.addForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var validatorPhone = function (rule, value, callback) {
        if (value === '') {
          callback(new Error('手机号不能为空'))
        } else if (!/^1\d{10}$/.test(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return{
        tableData:[],
        queryInfo:{
          userName:'',
          name:'',
          pageNumber:1,
          pageSize:10,
        },
        total:10,
        dialogVisible:false,
        addForm:{
          username:'',
          password:'',
          checkPass:'',
          name:'',
          email:'',
          post:'',
          roles:[],
          unitId:'',
          telephone:'',
        },
        addFormRule:{
          username:[{required:true,message:'请输入用户名',trigger:'blur'},{min:3,max:20,message:"用户名的长度再3-20个字符之间",trigger:'blur'}],
          password:[{required:true,message:'请输入密码',trigger:'blur'},{min:3,max:20,message:"密码的长度再8-30个字符之间",trigger:'blur'},{
            trigger: 'blur',
            validator: (rule, value, callback) => {
              var passwordreg = /^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{8,30}$/
              console.log(passwordreg.test(value))
              if (!passwordreg.test(value)) {
                callback(new Error('密码必须由大写字母、小写字母、数字、特殊符号中的3种及以上类型组成!'))
              }
              else{
                callback()
              }
            } },
          ],
          checkPass: [{ validator: validatePass2, trigger: 'blur' },{required:true,message:'请输入密码',trigger:'blur'}],
          email:[{validator:checkEmail,trigger:'blur'}],
          name:[{required:true,message:'请输入真实姓名',trigger:'blur'}],
          roles:[{required:true,message:'请选择角色',trigger:'blur'}],
          telephone:[{required:true,validator: validatorPhone,trigger:'blur'}],
          unitId:[{required:true,message:'请选择部门',trigger:'blur'}],
        },
        editdialogVisible:false,
        editForm:{
        },
        editFormRules:{
          /*password:[{required:true,message:'请输入密码',trigger:'blur'},{min:3,max:20,message:"密码的长度再3-20个字符之间",trigger:'blur'}],*/
          ///username:[{required:true,message:'请输入用户名',trigger:'blur'},{min:3,max:20,message:"用户名的长度再3-20个字符之间",trigger:'blur'}],
          name:[{required:true,message:'请输入真实姓名',trigger:'blur'}],
          roles:[{required:true,message:'请选择角色',trigger:'blur'}],
          email:[{validator:checkEmail,trigger:'blur'}],
          unitId:[{required:true,message:'请选择部门',trigger:'blur'}],
          telephone:[{required:true,validator: validatorPhone,trigger:'blur'}],
        },
        roleList:[],
        bumenList:[],
        juese:[],
        jueseEdit:[],
        bumen:[],
        bumenEdit:'',
      }
    },
    created () {
      this.getUserList();
      this.getRole();
      this.getBumen();
    },
    methods:{
      async getUserList(){
        const {data:res}=await  this.$http3.get('/v1.0/user/findPages',{
          params:this.queryInfo
        })
        if(res.status!=="3000"){
          return this.$message.error('获取用户列表失败！'+res.message)
        }
        this.tableData=res.data.result;
        this.total=res.data.totalCount
      },
      async getRole(){
        const {data:res}=await  this.$http3.get('/v1.0/role/findAll');
        if(res.status!=="3000"){
          return 0;
        }
        this.roleList=res.data;
      },
      async getBumen(){
        const {data:res}=await  this.$http3.get('/v1.0/unit/findAll');
        if(res.status!=="3000"){
          return 0;
        }
        this.bumenList=res.data;
      },
      handleSizeChange(newSize){
        this.queryInfo.pageSize=newSize;
        this.getUserList()
      },
      handleCurrentChange(newPage){
        this.queryInfo.pageNumber=newPage;
        this.getUserList()
      },
      dialogClose(){
        this.$refs.addFormRef.resetFields();
        this.juese=[];
        this.bumen='';
      },
      async addUser(){
        this.$refs.addFormRef.validate(async valid =>{
          if(!valid)
            return
         // this.addForm.password=md5(this.addForm.password)
          const {data:res}= await this.$http3.post('/v1.0/user/save', this.addForm)
          if(res.status!=="6000"){
            console.log(res)
           return this.$message.error('添加用户失败！'+res.message)
          }
          this.$message.success('添加用户成功！');
          this.getUserList();
          this.dialogVisible = false;
        })

      },
      async editDialog(id){
        //请求查询
        const {data:res}=await  this.$http3.get('/v1.0/user/findById/'+id);
        if(res.status!=="3000"){
          return 0;
        }
        this.editForm=res.data;
        this.jueseEdit=[];
        for(let i=0;i<res.data.roles.length;i++){
          this.jueseEdit.push(res.data.roles[i].id);
        }
        console.log(this.jueseEdit)
        this.editdialogVisible = true
      },
      //重置修改表单
      editdialogClose(){
        this.$refs.editFormRef.resetFields()
      },
      editUserInfo(){
        this.$refs.editFormRef.validate(async valid =>{
          console.log(this.editForm)
          if(!valid) return
          const {data:res}= await this.$http3.post('/v1.0/user/update', this.editForm)
          if(res.status!=="6000"){
           return this.$message.error('修改用户失败！')
          }
          this.$message.success('修改用户成功！');
          this.getUserList();
          this.editdialogVisible = false
        })
      },
      async deleteMsg(id){
        const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch((err) => {
          return err
        });
        if(confirmResult !== 'confirm'){
          return this.$message({
            type: 'info',
            message: '已取消删除'
          });
        }
        //请求
        const {data:res}= await this.$http3.delete('/v1.0/user/delete/'+id)
        if(res.status!="4000"){
         return this.$message.error('删除用户失败！')
        }
        this.$message.success('删除用户成功！');
        this.getUserList();
      },
      jueseChange(e){
        this.addForm.roles=[];
        for(let i=0;i<e.length;i++){
          this.addForm.roles.push({id:e[i]})
        }
      },
      jueseChange2(e){
        this.editForm.roles=[];
        for(let i=0;i<e.length;i++){
          this.editForm.roles.push({id:e[i]})
        }
      },
      bumenChange(e){
        this.addForm.unitId=e
      },
      bumenChange2(e){
        this.editForm.unitId=e
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      }
    }
  }
</script>

<style scoped lang="less">
  #yhList{
    position: absolute;
    left: 15.5%;
    top: 9.5%;
    bottom: 1.5%;
    width: 83.5%;
    /*background-color: #ffffff;*/
    border-radius: 8px;
    box-shadow: 0 0 5px #acc4fe;
  }
  ::v-deep .cell{
    text-align: center;
  }
  .el-row{
    ::v-deep  .el-input__inner{
      border-radius: 45px;
    }
    ::v-deep .el-button:focus, .el-button:hover {
      color: #fff;
      border-color: #c6e2ff;
      background: -webkit-linear-gradient(left,#3ee8c2,#25e4a3);
    }
    ::v-deep .el-button--goon:active {
      color: #fff;
      border-color: #c6e2ff;
      outline: 0;
    }
  }
  /deep/ .el-input-group__append{
    border-radius: 45px;
  }
  /deep/ .el-table th.gutter{
    display: table-cell!important;
  }
  /deep/ .el-dialog{
    border-radius: 8px;
  }
  /deep/ .el-dialog__header {
    //background: -webkit-linear-gradient(left, #3ee8c2, #25e4a3);
    border-radius: 8px 8px 0 0 ;
  }

  ::v-deep .el-button--goon:focus, .el-button--goon:hover {
    color: #fff;
    border-color: #c6e2ff;
    background: -webkit-linear-gradient(left,#3ee8c2,#25e4a3);
  }
  ::v-deep .el-button--goon:active {
    color: #fff;
    border-color: #c6e2ff;
    outline: 0;
  }
  ::v-deep .el-dialog__title{
    font-weight: bold;
    font-size: 20px;
    color: #45524f;
  }
  .el-dialog__body{
    .el-form{
      .el-form-item {
        .el-form-item__content{
          .el-input{
            ::v-deep  .el-input__inner{
              border-radius: 45px;
            }
          }

        }
      }
    }
  }
  /deep/ .el-select .el-input__inner{
    border-radius: 45px;
  }

  ::v-deep .el-form-item__content{
    ::v-deep  .el-input__inner{
      border-radius: 45px;
    }
  }
  ::v-deep .el-form-item__label{
    color: #45524f;
  }

  .serverTable{
    position: absolute;
    width: 97%;
    padding: 0%;
    /*height: 100%;*/
    height: calc(100% - 140px);
  }
  /deep/ .cell{
    text-align: center;
  }
  /deep/ .el-table__empty-text{
    line-height:44px
  }
  /deep/ .el-table__empty-block{
    min-height: 44px;
  }
  /deep/ .el-table__body-wrapper {
    /*height: 200px; !* 滚动条整体高 必须项 *!*/
    border-right: none;
    overflow-y: scroll;/* overflow-y为了不出现水平滚动条*/
  }
  /deep/ .el-dialog--center .el-dialog__body{
    padding: 10px;
  }
  /deep/ .el-table__body-wrapper::-webkit-scrollbar {
    width:6px;/* 滚动条的宽高 必须项 */
    height: 5px;
  }

  /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #bfcbd9;/* 滚动条的宽 */
    border-radius: 3px;
  }
</style>
